// utils/util.js
// 工具函数

/**
 * 格式化时间
 */
function formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

/**
 * 格式化日期
 */
function formatDate(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()

    return `${[year, month, day].map(formatNumber).join('-')}`
}

/**
 * 补零
 */
function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

/**
 * 相对时间
 */
function relativeTime(timestamp) {
    const now = Date.now()
    const diff = now - timestamp

    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour
    const month = 30 * day

    if (diff < minute) {
        return '刚刚'
    } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前'
    } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前'
    } else if (diff < month) {
        return Math.floor(diff / day) + '天前'
    } else {
        return formatDate(new Date(timestamp))
    }
}

/**
 * 防抖函数
 */
function debounce(fn, delay = 500) {
    let timer = null
    return function (...args) {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}

/**
 * 节流函数
 */
function throttle(fn, delay = 500) {
    let lastTime = 0
    return function (...args) {
        const now = Date.now()
        if (now - lastTime >= delay) {
            fn.apply(this, args)
            lastTime = now
        }
    }
}

/**
 * 安全的日期转换 (兼容iOS)
 */
function safeDate(dateStr) {
    if (!dateStr) return new Date()
    if (typeof dateStr === 'string') {
        // 尝试解决 iOS 下无法识别 2020-01-01 格式的问题
        // 如果是 ISO 格式 (包含 T)，通常 iOS 支持，但为了保险，可以尝试标准转换
        // 如果是普通 'YYYY-MM-DD HH:mm:ss' 格式，必须替换 - 为 /
        if (dateStr.includes('-') && !dateStr.includes('T')) {
            return new Date(dateStr.replace(/-/g, '/'))
        }
    }
    return new Date(dateStr)
}

module.exports = {
    formatTime,
    formatDate,
    formatNumber,
    relativeTime,
    debounce,
    throttle,
    safeDate
}
